<?php

namespace app\manystore\controller;

use app\common\controller\ManystoreBase;
use think\Db;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Integralorder extends ManystoreBase
{

    /**
     * Order模型对象
     * @var \app\manystore\model\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\manystore\model\Order;
        $this->view->assign("orderStatusList", $this->model->getOrderStatusList());
        $this->view->assign("orderAttributesList", $this->model->getOrderAttributesList());
        $this->view->assign("orderTypeList", $this->model->getOrderTypeList());
        $this->view->assign("payStatusList", $this->model->getPayStatusList());
        $this->view->assign("freightStatusList", $this->model->getFreightStatusList());
        $this->view->assign("receiptStatusList", $this->model->getReceiptStatusList());
        $this->view->assign("refundStatusList", $this->model->getRefundStatusList());
        $this->view->assign("commentStatusList", $this->model->getCommentStatusList());
        $this->view->assign("regionTypeList", $this->model->getRegionTypeList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['user'])
                    ->where($where)
                    ->where(['order_type'=>'20'])
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
				$row->getRelation('user')->visible(['nickname','avatar']);
                $goods = db('order_goods')->where(['order_id'=>$row->id])->order('id asc')->find();
                $row['goods_images'] = explode(',', $goods['images'])[0];
                $row['goods_name'] = $goods['goods_name'];
                $row['name'] = $row['name'].':'.$row['mobile'];
                $total_num = db('order_goods')->where(['order_id'=>$row->id])->sum('total_num');
                $row['total_price'] = 'HK$'.$row['total_price'].'('.$total_num.'件)';
                // $row['avatar'] = $row['user']['avatar'];
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }

        $this->assignconfig("order_edit", $this->auth->check("integralorder/edit"));
        $this->assignconfig("order_cancel", $this->auth->check("integralorder/cancel"));
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function cancel($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }

        $time = time();
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            if($this->shopIdAutoCondition){
                $this->model->where(array('shop_id'=>SHOP_ID));
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->save(['order_status'=>'50','canceltime'=>$time]);
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if($this->shopIdAutoCondition){
            $this->model->where(array('shop_id'=>SHOP_ID));
        }
        $row = $this->model->where(array('id'=>$ids))->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $row['goods'] = $goods = db('order_goods')->where(['order_id'=>['in',$row['id']]])->select();
        $row['total_num'] = db('order_goods')->where(['order_id'=>['in',$row['id']]])->sum('total_num');
        $user = db('user')->field('*')->where(['id'=>$row['user_id']])->find();
        $this->view->assign("user", $user);
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                // 發貨
                $expressquery = db('expressquery')->where(['id'=>$params['express']])->find();
                $params['express'] = $expressquery['express'];
                $params['expressname'] = $expressquery['name'];
                $params['order_status'] = '30';
                $params['freight_status'] = '20';
                $params['freighttime'] = time();
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    sendMessage(1,'您的訂單'.$row['order_no'].'已發貨','',$row['user_id'],4,$row['id']);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }



}
